package com.strongbj.iot.devices.newlight.request.handle;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.common.Executer;
import com.strongbj.iot.devices.newlight.common.NetMapping;
import com.strongbj.iot.devices.newlight.entity.BindNum;
import com.strongbj.iot.devices.newlight.entity.BindTagData;
import com.strongbj.iot.devices.newlight.entity.BindTagReturnData;
import com.strongbj.iot.devices.newlight.entity.Reader;
import com.strongbj.iot.devices.newlight.entity.T;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightOSMessageFactory;
import com.strongbj.iot.devices.newlight.response.handle.LowBatteryResponseHandle;
import com.strongbj.iot.devices.newlight.service.ReaderService;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 标签绑定事件
 * 
 * @author lei_w
 *
 */
public class BindTagHandle implements IMessageHandle<NewLightMQMessage, Object> {

	private static Logger logger = LogManager.getLogger(LowBatteryResponseHandle.class.getName());

	private ReaderService readerService = (ReaderService) ContextUtils.getBean("readerService");

	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	private NewLightOSMessageFactory newLightOSMessageFactory = (NewLightOSMessageFactory) ContextUtils
			.getBean("newLightOSMessageFactory");

	@Override
	public boolean isHandle(NewLightMQMessage msg) {
		if (msg.getActioncode().equals("bindTag")) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightMQMessage msg) {
		logger.info("====收到标签绑定====");
		BindTagData data = ((JSONObject) msg.getPostdata()).toJavaObject(BindTagData.class);
		BindNum bn = readerService.getBindNumByCode(data.getReaderCode());
		NewLightMQMessage mes = new NewLightMQMessage();
		mes.setActioncode("bindTagReturn");
		mes.setGUID(msg.getGUID());
		BindTagReturnData brd = new BindTagReturnData();
		if (bn.getNum() >= 800) {
			brd.setErrorMessage("设备绑定的标签已超过最大数800个，无法绑定。");
			brd.setSendBindCommandSuccess(false);
		} else {
			QueryWrapper<Reader> query = new QueryWrapper<>();
			query.eq("code_", data.getReaderCode());
			Reader reader = readerService.getOne(query);
			if (reader != null) {
				// 循环发送标签绑定命令
				for (int i = 0; i < data.getTags().size(); i++) {
					byte[] sendData = new byte[6];
					String tag = data.getTags().get(i);
					byte[] d = ByteUtil.ipToBytesByInet(tag);
					System.arraycopy(d, 0, sendData, 0, 4);
					sendData[4] = 0x3e;
					sendData[5] = 0x00;
					byte[] timeStamp = T.getTimeStamp();
					byte[] req = newLightOSMessageFactory.createNewLightOSMessage(
							ByteUtil.addressToBytes(data.getReaderCode()), (byte) 0x02, sendData, timeStamp);
					ByteBuf bs = Unpooled.copiedBuffer(req);
					
					//使用队列发送点亮命令
					Map<String,Object> args = new HashMap<String,Object>();
					args.put("code", reader.getCode());
					args.put("tag", tag);
					args.put("req", req);
					Executer.RunCmd("BindTag", reader.getIp(), bs, args, timeStamp);
					
//					Channel channel = NetMapping.getInstance().getChannel(reader.getIp());
//					ChannelFuture cf = channel.writeAndFlush(bs);
//					cf.addListener(new ChannelFutureListener() {
//
//						@Override
//						public void operationComplete(ChannelFuture future) throws Exception {
//							if (future.isSuccess()) {
//								logger.info("发送绑签命令成功 设备编号:{} 标签编号:{} 命令={}  ", reader.getCode(),
//										tag, ByteUtil.byteArrToHexString(req, true));
//							} else {
//								logger.debug("发送绑签命令失败 设备编号:{} 标签编号:{} 命令={}  ", reader.getCode(),
//										tag, ByteUtil.byteArrToHexString(req, true));
//							}
//						}
//
//					});
				}
				brd.setSendBindCommandSuccess(true);
			} else {
				brd.setSendBindCommandSuccess(false);
				brd.setErrorMessage("Reader设备未找到。");
			}
		}
		brd.setReaderCode(data.getReaderCode());
		brd.setTags(data.getTags());

		mes.setPostdata(brd);
		logger.info("=========bindTagReturn=======" + JSON.toJSONString(mes));
		topicSender.send("wh.reader.command.response", JSON.toJSONString(mes));
		return mes;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub

	}

}
